import CommonDrawer from '@/components/CommonDrawer';
import { GroupTreeSelect } from '@/components/CustomForm';
import TableTransfer from '@/components/TableTransfer';
import request from '@/utils/request';
import { useRequest } from 'ahooks';
import { Form } from 'antd';
import { useEffect } from 'react';

const QuickAdd = (props) => {
  const { lineId, open, onCancel, onOk } = props;
  const [form] = Form.useForm();

  const { data, runAsync, mutate } = useRequest(
    async (params) => {
      const res = await request({
        url: params.groupId
          ? '/operating/trip/realtime/vehicle/bind/list'
          : '/datas/vehicle/task/line/list',
        method: 'GET',
        params,
      });
      return res.map((item) => ({
        ...item,
        key: item.vehicleId,
      }));
    },
    {
      manual: true,
    },
  );

  const groupId = Form.useWatch('groupId', form);

  useEffect(() => {
    if (open && (lineId || groupId)) {
      form.resetFields(['list']);
      runAsync({
        lineId,
        groupId,
      });
    }
  }, [lineId, groupId, open, runAsync]);

  const handleOk = () => {
    const values = form.getFieldsValue();
    const valueList = data?.filter((item) =>
      values?.list?.includes?.(item.vehicleId),
    );
    onOk?.(valueList);
  };
  const columns = [
    {
      title: '组织',
      dataIndex: 'groupName',
      width: 200,
    },
    {
      title: '车牌号',
      dataIndex: 'license',
      width: 120,
    },
    {
      title: '驾驶员',
      dataIndex: 'realname',
      width: 140,
    },
  ];
  return (
    <CommonDrawer
      title="快速添加"
      width={1150}
      open={open}
      onClose={onCancel}
      onOk={handleOk}
      afterOpenChange={(visible) => {
        if (!visible) {
          form.resetFields();
          mutate();
        }
      }}
      destroyOnHidden
    >
      <div>
        <Form form={form} layout="horizontal">
          <Form.Item label="组织" name="groupId">
            <GroupTreeSelect
              onChange={(val) => {
                runAsync({
                  groupId: val,
                  lineId: form.getFieldValue('lineId'),
                });
              }}
            />
          </Form.Item>
          <Form.Item noStyle name="list">
            <TableTransfer
              rowKey="vehicleId"
              dataSource={data}
              leftColumns={columns}
              rightColumns={columns}
            />
          </Form.Item>
        </Form>
      </div>
    </CommonDrawer>
  );
};

export default QuickAdd;
